package com.itheima.threadDemo;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Demo6 {
    public static void main(String[] args) {
        //创建对象
        Ticket ticket = new Ticket();
        Thread t1 = new Thread(ticket);
        Thread t2 = new Thread(ticket);
        Thread t3 = new Thread(ticket);
        //设置名称
        t1.setName("窗口一");
        t2.setName("窗口二");
        t3.setName("窗口三");
        //调用方法
        t1.start();
        t2.start();
        t3.start();
    }
}

class Ticket implements Runnable {
    private int ticket = 100;
    //private Object obj = new Object();
    //定义锁,多态语法ReentrantLock
    private Lock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            // synchronized (obj) {
            //上锁
            lock.lock();
            if (ticket <= 0) {
                break;
            } else {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                ticket--;
                System.out.println(Thread.currentThread().getName() + "还剩" + ticket + "张票");
                //解锁
                lock.unlock();
            }
            //   }
        }
    }
}